//
//  WZProgressViewController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/8/31.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZProgressViewController.h"
#import "JKAlertDialog.h"


#define TaskManager_taskProgress                  @"任务进度不能为空"
#define TaskManager_taskProgress_Info             @"进度说明不能为空"
#define TaskManager_taskProgress_SaveSuccess      @"保存成功"
#define TaskManager_taskProgress_BackItem_Message @"您尚未保存进度,确定退出?"
#define TaskManager_taskProgress_BackItem_Cancel  @"取消"
#define TaskManager_taskProgress_BackItem_Done    @"确定"
#define TaskManager_taskFinishWithProgress        @"进度未达到100%"
#define TaskManager_TextView_Progress             @"进度说明"

@interface WZProgressViewController ()<UITextViewDelegate, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *progressTF;
@property (weak, nonatomic) IBOutlet UITextView *progressTextView;
@property (weak, nonatomic) IBOutlet UILabel *characterCount;

@end

@implementation WZProgressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupProgress];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [_progressTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    [_progressTF becomeFirstResponder];
}

- (void)setupProgress {
    
    self.view.backgroundColor = RGBCOLORWITH16COLOR(0xf5f5f5);
    self.navigationItem.title = @"提交进度";
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(backBtnDidClick) titleFont:Font18 titleColor:WhiteColor];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"taskManager_refuse_nav_right" title:nil target:self sel:@selector(saveProgressBtnDidClick) titleFont:Font12 titleColor:WhiteColor];
    
//    self.navigationItem.rightBarButtonItem.enabled = NO;
    self.progressTF.text = _progress;
}


- (void)saveProgressBtnDidClick {
    
    if (![_progressTextView.text isEqualToString:TaskManager_TextView_Progress] && _progressTF.text.length) {
        
        [self saveProgress];
        
    } else {
        
        if (!_progressTF.text.length) {
            
            [MBProgressHUD showError:TaskManager_taskProgress];
            return;
        }
        
        if (!_progressTextView.text.length || [_progressTextView.text isEqualToString:TaskManager_TextView_Progress]) {
            [MBProgressHUD showError:TaskManager_taskProgress_Info];
            return;
        }
    }
}

/**保存进度*/
- (void)saveProgress {
    
    [MBProgressHUD showMessage:@"正在保存..." toView:self.view];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"name"] = self.oaUserName;
    params[@"pwd"] = self.oaPwd;
    params[@"taskId"] = self.taskId;
    params[@"progress"] = self.progressTF.text;
    params[@"progressRemark"] = self.progressTextView.text;
    
    [NetWorkShare saveProgressWithParams:params SuccessHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            if ([responseObject objectForKey:@"success"]) {
                
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showSuccess:TaskManager_taskProgress_SaveSuccess];
                
                if (_block) {
                    
                    _block(_progressTF.text);
                }
                
                [self.navigationController popViewControllerAnimated:YES];
                
                WZLog(@"result = %@", responseObject);
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
        } else {
            
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:UNKNOWNERROR];
        }
    } FailureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:NETWORKNERROR];
        WZLog(@"error = %@", error);
    }];
}

#pragma mark - 隐藏键盘

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.progressTextView resignFirstResponder];
    [self.view endEditing:YES];
    [super touchesBegan:touches withEvent:event];
}

#pragma mark - textView Delegate

- (void)textViewDidChange:(UITextView *)textView {
    
    WZLog(@"textViewDidChange");
    
    if (textView.text.length <= 500) {
        self.characterCount.text = [NSString stringWithFormat:@"%lu/500", 500 - textView.text.length];
        
    } else {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            textView.text = [textView.text substringToIndex:500];
            _characterCount.text = @"0/500";
            [textView endEditing:YES];
        });
    }
}



- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if(range.location > 500){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"输入的自字符数不能超过500"
                                                       delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
        
    }else{
        
        return YES;
    }
}

- (NSUInteger) unicodeLengthOfString: (NSString *) text {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    NSUInteger unicodeLength = asciiLength / 2;
    if(asciiLength % 2) {
        unicodeLength++;
    }
    return unicodeLength;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
    WZLog(@"textViewShouldBeginEditing");
    
    return YES;
}


- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    WZLog(@"DidBeginEditing");
    
    if ([textView.text isEqualToString:TaskManager_TextView_Progress]) {

        textView.text = @"";
        [textView setTextColor:[UIColor blackColor]];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    WZLog(@"textViewDidEndEditing");
    
    if (textView.text.length < 1) {
        
        textView.text = TaskManager_TextView_Progress;
        [textView setTextColor:[UIColor grayColor]];
        textView.backgroundColor = WZRGBColor(247, 246, 250);
    }
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    
//    [textView setBackgroundColor:[UIColor redColor]];
    WZLog(@"textViewShouldEndEditing");
    
    return YES;
}


#pragma mark - TextFieldDelegate 

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [_progressTF resignFirstResponder];
    return YES;
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
//    if ([textField.text intValue] > 100) {
//        textField.text = @"100";
//        return NO;
//    }
    return YES;
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.progressTF) {
        if (textField.text.length > 3) {
            textField.text = [textField.text substringToIndex:3];
        }
        
        if ([_progressTF.text isEqualToString:@"100"] || [_progressTF.text intValue] > 100) {
            textField.text = @"100";
        }
    }
}


#pragma mark - 返回按钮点击方法
- (void)backBtnDidClick {
    
    [_progressTextView endEditing:YES];
    
    if ([_progressTextView.text isEqualToString:TaskManager_TextView_Progress]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    __block WZProgressViewController *block = self;
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:TaskManager_taskProgress_BackItem_Message];
    [alert addButton:Button_OK withTitle:TaskManager_taskProgress_BackItem_Done handler:^(JKAlertDialogItem *item) {
        
//        [block saveProgress];
        [block.navigationController popViewControllerAnimated:YES];
    }];
    
    [alert addButton:Button_CANCEL withTitle:TaskManager_taskProgress_BackItem_Cancel handler:^(JKAlertDialogItem *item) {
        
        
    }];
    
    [alert show];
}


@end
